//
//  MainViewController.swift
//  MyProject
//
//  Created by volantPig on 2020/11/10.
//

import UIKit

class MainViewController: UIViewController {

    var myTableView: UITableView?
    var currentDataSoucre: DataSourceModel?
    var currentKeys: [String]?
    
    var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.setNavigationBarItem()
        self.createUIElements()
        timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(getNetData), userInfo: nil, repeats: true)
        
        // Do any additional setup after loading the view.
    }
    
    /// 布局UI元素
    func createUIElements() {
        myTableView = UITableView.init(frame: .zero, style: .plain)
        self.view.addSubview(myTableView!)
        myTableView?.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            myTableView!.leftAnchor.constraint(equalTo: self.view.leftAnchor),
            myTableView!.topAnchor.constraint(equalTo: self.view.topAnchor),
            myTableView!.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
            myTableView!.rightAnchor.constraint(equalTo: self.view.rightAnchor)
        ])
        myTableView?.delegate = self
        myTableView?.dataSource = self
        myTableView?.register(UITableViewCell.self, forCellReuseIdentifier: "myCell")
    }
    
    /// 获取网络数据
    @objc func getNetData() {
        NetworkManager.getRequest(url: "https://api.github.com/", params: nil) { (responseStr) in
            DBHelper.default.save(responseStr)
            print("获取数据:\(responseStr)")
            if let model = DataSourceModel.deserialize(from: responseStr, designatedPath: "") {
                self.currentDataSoucre = model
                self.currentKeys = self.currentDataSoucre?.toJSON()?.keys.sorted()
                self.myTableView?.reloadSections(.init(arrayLiteral: 0), with: .fade)
                DispatchQueue.main.asyncAfter(deadline: .now()+2) {
                    self.currentDataSoucre = nil
                    self.currentKeys = nil
                    self.myTableView?.reloadSections(.init(arrayLiteral: 0), with: .fade)
                }
            }
        } requestAnomalyBlock: { (stateCode) in
            print("服务器返回异常:\(stateCode)")
        } requestFailureBlock: { (error) in
            print("请求失败:\(error)")
        }
    }
    
    func setNavigationBarItem() {
        let moreButton = UIButton.init(type: .system)
        moreButton.setTitle("历史信息", for: UIControl.State.normal)
        moreButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        moreButton.addTarget(self, action: #selector(rightAction), for: .touchUpInside)
        
        let barButtonItem = UIBarButtonItem.init(customView: moreButton)
        self.navigationItem.rightBarButtonItem = barButtonItem
        
        let stopRequestButton = UIButton.init(type: .system)
        stopRequestButton.setTitle("停止请求", for: .normal)
        stopRequestButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        stopRequestButton.addTarget(self, action: #selector(stopRequestAction), for: .touchUpInside)
        
        let leftBarButtonItem = UIBarButtonItem.init(customView: stopRequestButton)
        self.navigationItem.leftBarButtonItem = leftBarButtonItem
        
    }
    
    @objc func rightAction() {
        let historyVC = HistoryViewController()
        self.navigationController?.pushViewController(historyVC, animated: true)
    }
    
    @objc func stopRequestAction() {
        self.timer?.invalidate()
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension MainViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.currentKeys?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell")
        
        for subV in (cell?.subviews ?? [UIView]()) {
            subV.removeFromSuperview()
        }
        
        let keyLabel = UILabel()
        keyLabel.translatesAutoresizingMaskIntoConstraints = false
        cell?.addSubview(keyLabel)

        NSLayoutConstraint.activate([
            keyLabel.leftAnchor.constraint(equalTo: cell!.leftAnchor, constant: 10),
            keyLabel.rightAnchor.constraint(equalTo: cell!.rightAnchor, constant: -10),
            keyLabel.topAnchor.constraint(equalTo: cell!.topAnchor, constant: 10)
        ])
        keyLabel.textColor = .black
        keyLabel.font = UIFont.systemFont(ofSize: 16)
        keyLabel.text = "数据异常"
        keyLabel.numberOfLines = 0
        
        let valueLabel = UILabel()
        valueLabel.translatesAutoresizingMaskIntoConstraints = false
        cell?.addSubview(valueLabel)
        NSLayoutConstraint.activate([
            valueLabel.leftAnchor.constraint(equalTo: cell!.leftAnchor, constant: 10),
            valueLabel.rightAnchor.constraint(equalTo: cell!.rightAnchor, constant: -10),
            valueLabel.topAnchor.constraint(equalTo: keyLabel.bottomAnchor, constant: 10),
            valueLabel.bottomAnchor.constraint(equalTo: cell!.bottomAnchor, constant: -10)
        ])
        valueLabel.textColor = .black
        valueLabel.font = UIFont.systemFont(ofSize: 16)
        valueLabel.text = "数据异常"
        valueLabel.numberOfLines = 0
        
        if let key = self.currentKeys?[indexPath.row] {
            keyLabel.text = String.init(format: "key: %@", key)
            let value = self.currentDataSoucre?.toJSON()?[key] as? String
            valueLabel.text = String.init(format: "value: %@", value ?? "")
        
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard  let key = self.currentKeys?[indexPath.row] else {
            return
        }
        print("点击key:\(key)")
        let value = self.currentDataSoucre?.toJSON()?[key] as? String
        print("点击value:\(String(describing: value))")

    }
}
